<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useUserStore } from "@/stores/user";
import { useRoute } from 'vue-router';
import { getConversationId, getHistoryMessage } from '@/api/Chat.js'; // 假设后端查询会话ID和历史消息接口

const route = useRoute();
const userStore = useUserStore();

// 获取路径中的接收方 userId 和用户名
const receiverId = route.query.userId;
const receiverName = route.query.username;

// 当前用户的用户ID
const senderId = userStore.UserId;

// 保存会话 ID
const conversationId = ref(null);

// 消息列表
const messageList = ref([]);

// WebSocket 对象
const websocket = ref(null);

// 用于发送的消息输入框的内容
const newMessage = ref('');

// WebSocket 连接的建立
const setupWebSocket = () => {
  const wsUrl = `ws://localhost:8080/imserver/${userStore.UserId}`;
  websocket.value = new WebSocket(wsUrl);

  websocket.value.onmessage = (event) => {
    const receivedMessage = JSON.parse(event.data);
    handleIncomingMessage(receivedMessage);
  };

  websocket.value.onclose = () => {
    console.log('WebSocket connection closed');
  };
};

// 处理接收到的消息
const handleIncomingMessage = (message) => {
  console.log('Received message:', message);

  // 判断接收到的消息是否属于当前会话
  if (conversationId.value === parseInt(message.conversationId)) {
    const newMsg = {
      messageId: Date.now(),  // 用于生成一个临时的唯一ID
      conversationId: message.conversationId,
      senderId: message.from,
      receiverId: senderId,
      text: message.text
    };
    messageList.value = [...messageList.value, newMsg];
  } else {
    console.log('收到新消息，但不是当前会话:', message);
  }
};

// 发送消息
const sendMessage = () => {
  if (newMessage.value.trim() === '' || !conversationId.value) return;

  const messageData = {
    from: senderId,
    to: receiverId,
    text: newMessage.value,
    conversationId: conversationId.value
  };

  if (websocket.value && websocket.value.readyState === WebSocket.OPEN) {
    websocket.value.send(JSON.stringify(messageData));
    const localMessage = {
      messageId: Date.now(),  // 用于生成一个临时的唯一ID
      conversationId: conversationId.value,
      senderId: senderId,
      receiverId: receiverId,
      text: newMessage.value
    };
    messageList.value = [...messageList.value, localMessage];
    newMessage.value = ''; // 发送后清空输入框
  }
};

// 获取会话ID并查询历史消息
const fetchConversationAndHistory = async () => {
  const conversationIdRes = await getConversationId(userStore.UserId, receiverId);
  console.log('Conversation ID:', conversationIdRes);

  // 查询历史消息
  const historyMessageRes = await getHistoryMessage(conversationIdRes.data.data);
  console.log('History Message:', historyMessageRes);

  conversationId.value = conversationIdRes.data.data;
  messageList.value = historyMessageRes.data.data;
};

// 生命周期钩子，组件挂载时执行
onMounted(() => {
  fetchConversationAndHistory(); // 获取会话ID并查询历史记录
  setupWebSocket(); // 初始化 WebSocket 连接
});

// 组件卸载时关闭 WebSocket 连接
onUnmounted(() => {
  if (websocket.value) {
    websocket.value.close();
  }
});

// Get message alignment based on sender
const isUserMessage = (message) => {
  return message.senderId === userStore.UserId;
};

</script>

<template>
  <div class="chat-container">
    <!-- 显示聊天对象 -->
    <div class="chat-header">
      <h2>与 {{ receiverName }} 的对话</h2>
    </div>

    <!-- Chatbox -->
    <div class="chat-box">
      <div class="message-list">
        <div v-for="(message, index) in messageList" :key="index"
             :class="['message-item', isUserMessage(message) ? 'message-right' : 'message-left']">
          <!-- Display the avatar -->
          <img v-if="!isUserMessage(message)" :src="userStore.avatar || 'default-avatar.png'" alt="Avatar"
               class="message-avatar">
          <img v-if="isUserMessage(message)" :src="userStore.avatar || 'default-avatar.png'" alt="Avatar"
               class="message-avatar">
          <!-- Display the message content -->
          <span class="message-content">{{ message.text }}</span>
        </div>
      </div>

      <!-- Message input and send button -->
      <div class="message-input">
        <input type="text" v-model="newMessage" placeholder="输入消息..." @keyup.enter="sendMessage" />
        <button @click="sendMessage">发送</button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 80vh;
  width: 150%;
  margin-left: 10%;
  background-color: #f4f4f9;
}

.chat-header {
  text-align: center;
  background-color: #fff;
margin-top: -10%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-bottom: 1px solid #e0e0e0;
}

.chat-box {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  padding: 10px;
  border-radius: 8px;
  overflow: hidden;
}

.message-list {
  flex-grow: 1;
  padding: 10px;
  overflow-y: auto;
}

.message-item {
  display: flex;
  align-items: center;
  margin: 10px 0;
  max-width: 70%;
  word-wrap: break-word;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.message-content {
  padding: 8px 12px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.4;
  background-color: #f1f1f1;
}

.message-left .message-content {
  background-color: #f1f1f1;
}

.message-right {
  margin-left: auto;
  flex-direction: row-reverse;
}

.message-right .message-avatar {
  margin-left: 10px;
  margin-right: 0;
}

.message-right .message-content {
  background-color: #b3e5fc;
}

.message-input {
  display: flex;
  gap: 10px;
  padding: 15px;
  background-color: #fff;
  border-top: 1px solid #ccc;
}

.message-input input {
  flex-grow: 1;
  padding: 10px;
  border-radius: 20px;
  border: 1px solid #ccc;
}

.message-input button {
  padding: 10px 20px;
  border-radius: 20px;
  background-color: #4caf50;
  color: white;
  border: none;
  cursor: pointer;
}

.message-input button:hover {
  background-color: #45a049;
}

.message-list::-webkit-scrollbar {
  width: 6px;
}

.message-list::-webkit-scrollbar-thumb {
  background-color: #b3e5fc;
  border-radius: 3px;
}
</style>
